package com.zahb.qadx.ui.activity;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.LinearLayoutCompat;
import androidx.core.view.ViewCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;
import com.zahb.qadx.R;
import com.zahb.qadx.base.BaseActivity;
import com.zahb.qadx.base.BaseApplication;
import com.zahb.qadx.model.AttentionModel;
import com.zahb.qadx.model.CommonResponse;
import com.zahb.qadx.net.RetrofitService;
import com.zahb.qadx.skeleton.RecyclerViewSkeletonScreen;
import com.zahb.qadx.skeleton.Skeleton;
import com.zahb.qadx.ui.adapter.AttentionAdapter;
import com.zahb.qadx.util.Constant;
import com.zahb.qadx.util.DisplayUtil;
import com.zahb.qadx.util.Tips;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * Created by huwei.
 * Data 2020-09-29.
 * Time 15:55.
 */
public class AttentionActivity extends BaseActivity implements AttentionAdapter.OnItemClickListener , OnRefreshLoadMoreListener {
    @BindView(R.id.recycler_view)
    RecyclerView recyclerView;
    @BindView(R.id.ll_empty)
    LinearLayoutCompat llEmpty;
    AttentionAdapter attentionAdapter;
    @BindView(R.id.refresh_layout)
    SmartRefreshLayout refreshLayout;
    private List<AttentionModel.AttentionData.AttentionList> dataList = new ArrayList<>();
    private Gson mGson = new Gson();
    AlertDialog alertDialog;
    private RecyclerViewSkeletonScreen mSkeletonScreen;
    private long mSkeletonShowTime;
    @Override
    protected int getLayout() {
        return R.layout.activity_attention;
    }

    @Override
    protected void initViews() {
        mUnbinder = ButterKnife.bind(this);
        refreshLayout.setOnRefreshLoadMoreListener(this);
        refreshLayout.setEnableLoadMoreWhenContentNotFull(false);
        refreshLayout.setEnableLoadMore(false);

        LinearLayoutManager managerGrid = new LinearLayoutManager(getActivity());
        recyclerView.setLayoutManager(managerGrid);
        attentionAdapter = new AttentionAdapter(getActivity(), dataList);
        attentionAdapter.setOnItemClickListener(this);
        recyclerView.setAdapter(attentionAdapter);
    }

    @Override
    protected int getTitleStringRes() {
        return R.string.mine_attention;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        onRefresh(refreshLayout);
        showSkeleton();
    }

    @Override
    protected void onResume() {
        super.onResume();
        //getData();
    }

    private void getAttentionData(CommonResponse<AttentionModel.AttentionData> response) {
        if (response.getStatusCode() == 200) {
            dataList.clear();
            dataList.addAll(response.getData().getList());
            attentionAdapter.notifyDataSetChanged();
            if (dataList.size() > 0) {
                isVisible(true);
            } else {
                isVisible(false);
            }
        } else {
            showBindToast(response.getErrorInfo());
        }
    }

    private void isVisible(boolean flag) {
        if (recyclerView.getAdapter() instanceof AttentionAdapter) {
            if (flag) {
                recyclerView.setVisibility(View.VISIBLE);
                llEmpty.setVisibility(View.GONE);
            } else {
                llEmpty.setVisibility(View.VISIBLE);
                recyclerView.setVisibility(View.GONE);
            }
        }
    }

    private final int padding = DisplayUtil.dip2px2(16f);

    private void showSkeleton() {
        refreshLayout.setEnableRefresh(false);
        mSkeletonScreen = Skeleton.bind(recyclerView)
                .adapter(attentionAdapter)
                .shimmer(true)
                .shimmerMode(RecyclerViewSkeletonScreen.SHIMMER_MODE_ITEM_CHILD)
                .angle(15)
                .frozen(true)
                //.color(R.color.black_333333)
                .duration(1000)
                .count(10)
                .load(R.layout.item_list_curriculum_skeleton)
                .show();
        ViewCompat.setPaddingRelative(recyclerView, padding, 0, padding, 0);
        mSkeletonShowTime = System.currentTimeMillis();
    }

    private void hideSkeleton() {
        if (mSkeletonScreen != null) {
            long currentTime = System.currentTimeMillis();
            if (currentTime - mSkeletonShowTime > Constant.MIN_NETWORK_TIME) {
                refreshLayout.setEnableRefresh(true);
                mSkeletonScreen.hide();
                mSkeletonScreen = null;
                ViewCompat.setPaddingRelative(recyclerView, 0, 0, 0, 0);
                isVisible(attentionAdapter.getItemCount() > 0);
            } else {
                addDisposable(Observable.timer(mSkeletonShowTime + Constant.MIN_NETWORK_TIME - currentTime, TimeUnit.MILLISECONDS)
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(aLong -> hideSkeleton()));
            }
        }
    }

    @Override
    public void onItemClick(View view, int position, String id) {
        CancelDialog(id);
    }

    private void CancelDialog(String id) {
        AlertDialog.Builder customizeDialog = new AlertDialog.Builder(getContext());
        alertDialog = customizeDialog.create();
        View dialogView = View.inflate(this, R.layout.item_cancel_attention, null);
        alertDialog.setCancelable(false);
        TextView cancel = dialogView.findViewById(R.id.tv_cancel);
        TextView ok = dialogView.findViewById(R.id.tv_ok);
        cancel.setOnClickListener(view -> alertDialog.dismiss());
        ok.setOnClickListener(view -> {
            getAttentionAndCancel(id);
            alertDialog.dismiss();
        });
        alertDialog.setView(dialogView);
        alertDialog.show();
    }

    private void getAttentionAndCancel(String id) {
        Map<String, Object> params = new HashMap<>();
        params.put("attentioType", 1); //关注类型 1讲师
        params.put("id", id); //关注列表id
        params.put("relationId", ""); // 管理id
        params.put("type", 1); //关注请求类型 0关注 1 取消关注
        String json = mGson.toJson(params);
        RequestBody body = RequestBody.create(MediaType.parse("application/json"), json);
        if (!TextUtils.isEmpty(BaseApplication.getContext().getToken())) {
            showProgressDialog("");
            addDisposable(RetrofitService.getNetService()
                    .getSaveorCancel(body)
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(response -> {
                        hideProgressDialog();
                        if (response.getStatusCode() == 200) {
                            showBindToast("取消关注成功");
                            getData();
                        } else {
                            showBindToast(response.getErrorInfo());
                        }
                    }, throwable -> {
                        hideProgressDialog();
                        throwable.printStackTrace();
                        Tips.RequestError(getActivity());
                    }));
        }
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        refreshLayout.finishLoadMore(1000);
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        getData();
    }
    private void getData(){
        Map<String, Object> params = new HashMap<>();
        params.put("attentioType", "1");
        params.put("pageNo", 1);
        params.put("pageSize", 99);
        params.put("relationId", "");
        String json = mGson.toJson(params);
        RequestBody body = RequestBody.create(MediaType.parse("application/json"), json);
        if (!TextUtils.isEmpty(BaseApplication.getContext().getToken())) {
            //showProgressDialog("");
            addDisposable(RetrofitService.getNetService()
                    .getUserAttention(body)
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(response -> {
                        hideProgressDialog();
                        getAttentionData(response);
                        refreshLayout.finishRefresh();
                        hideSkeleton();
                    }, throwable -> {
                        hideProgressDialog();
                        refreshLayout.finishRefresh();
                        throwable.printStackTrace();
                        Tips.RequestError(getActivity());
                        hideSkeleton();
                    }));
        }
    }
}
